/*
 * fileLockHelper.c
 *
 *  Created on: Oct 30, 2011
 *      Author: shaohong
 */


#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#include "logger.h"
#include "fileLockHelper.h"

/*
 * Acquire the given type of file lock for the given file
 ARGUMENT
 fd is the file descriptor of the given
 lockType is the type of lock to be acquired. i.e. F_RDLCK, F_WRLCK, F_UNLCK

 RETURN VALUE
 return 0 if successfully acquired the write lock, -1 other wise.
 */
int setFileLock(int fd, short lockType) {
	struct flock fl = {lockType, SEEK_SET, 0, 0, 0 };

	fl.l_pid = getpid();

	if (fcntl(fd, F_SETLKW, &fl) == -1) {

		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

/**
 * release the file lock on the given fd.
 */
int releaseFileLock(int fd) {
	return setFileLock(fd, F_UNLCK);
}
